﻿package extremefx.collections {
	import extremefx.IEnumerator;	
	import flash.utils.Dictionary;
	
	/**
	 * @author Marcelo Volmaro
	 */
	internal final class TPostEnum implements IEnumerator{
		private var _root:TreeNode;
		private var _node:TreeNode;
		private var _mode:Function;
		private var _visited:flash.utils.Dictionary;
		
		public function TPostEnum(pHead:TreeNode) {
			_root = pHead;
			reset();
		}
		
		private function _getMaxDepth(_pNode:TreeNode):TreeNode{
			while (_pNode._first) _pNode = _pNode._first;
			return _pNode;
		}
		public function moveNext():Boolean {
			var tmpNode:TreeNode;
			if (_node){
				if (_node == _root) {
					_node = null;
					
				} else if (_visited[_node]){
					if (_node._next){//has sibling, continue
						_node = _getMaxDepth(_node._next);
						 
					} else {//does not has sibling
						_node = _node._parent;
						_visited[_node] = true;
					}
					
				} else if ((tmpNode = _node._first)){//has childs, find first "last child".
					_node = _getMaxDepth(tmpNode);
					
				} else if (_node._next){//has sibling, continue
					_node = _node._next;
					  
				} else {//does not has sibling
					_node = _node._parent;
					_visited[_node] = true;
				}
				
			} else {
				_node = _getMaxDepth(_root);
			}
			
			return _node != null;		
		}
		
		public function reset():void {
			_node = null;
			_visited = new flash.utils.Dictionary(true);
		}
		
		public function get current():* {
			return _node;
		}
	}
}
